package cmd

import (
	"fmt"
	"io"
	"log"
	"os"
	"tools/mwapictl/internal/validate"

	"github.com/spf13/cobra"
)

var output bool
var validateCmd = &cobra.Command{
	Use:                   "validate [asyncapi-file]",
	Short:                 "Validate the asyncapi file",
	Args:                  cobra.MaximumNArgs(1),
	DisableFlagsInUseLine: true,
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Flags().BoolVar(&output, "output", true, "Write the parsed schema to file if validation pass")
		var filePath string
		if len(args) == 0 {
			filePath = "asyncapi.yaml"
		} else {
			filePath = args[0]
		}
		_, err := os.Stat(filePath)
		if err != nil {
			fmt.Println("Can't find file: " + filePath)
			os.Exit(1)
		}
		asyncapiCli := validate.New(filePath)
		parser, reader, err := asyncapiCli.NewParserAndReader()
		if err != nil {
			log.Fatal(err)
		}

		// declare a default reader
		var out io.Writer = nil
		// If specific output file path, write the parsed schema to the file
		if output {
			out, err = os.OpenFile("schema.json", os.O_RDWR|os.O_CREATE, 0644)
			if err != nil {
				fmt.Println("Can't create file: schema.json, error: " + err.Error())
				os.Exit(1)
			}
		}
		err = parser(reader, out)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		} else {
			fmt.Println("Validation Pass")
		}
	},
}
